﻿using Gp.Scripts.Core;
using Helpers;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Gp.GameLogic {
    public class DraggableItem : MonoBehaviour {
        [SerializeField] private Rigidbody handRig;
        [SerializeField] private Transform target;
        private Camera _myCamera;
        private ConfigurableJoint _joint;
        
        private float _tempDis;
        private void Start() {
            _myCamera = ObjectHelper.MainCamera;
            var o = new GameObject("obj");
            handRig = o.AddComponent<Rigidbody>();
            
            handRig.isKinematic = true;
            handRig.useGravity = false;

            target = transform;


            _ignoreLayer = LayerMask.NameToLayer("Ignore Raycast");
            _defaultLayer = LayerMask.NameToLayer("Default");
        }

        private void Hand(Vector2 mousePosition) {
            Ray ray = _myCamera.ScreenPointToRay(mousePosition);
            Debug.DrawRay(ray.origin, ray.direction * 100f, Color.red, 1f);
            bool b = Physics.Raycast(ray, out var hit, 10f);
            if (!b || hit.collider == null || hit.collider.gameObject != this.gameObject) return;
            
            handRig.transform.position = hit.point;
            if (_joint != null)
                Destroy(_joint);
            _joint = target.gameObject.AddComponent<ConfigurableJoint>();
            _joint.connectedBody = handRig;
            _joint.xMotion = ConfigurableJointMotion.Locked;
            _joint.yMotion = ConfigurableJointMotion.Locked;
            _joint.zMotion = ConfigurableJointMotion.Locked;
            _joint.anchor = _joint.transform.InverseTransformPoint(hit.point);
        }

        private void Move(Vector3 pos) {
            Ray ray = _myCamera.ScreenPointToRay(pos);

            var temp = transform.position.z;
            
            if (Physics.Raycast(ray, out var hit, 20f) && hit.collider.gameObject != gameObject) {
                handRig.transform.position = hit.point;
            }
            else {
                pos.z = temp;
                handRig.transform.position = pos;
            }

            _tempDis = temp;
        }


        private int _ignoreLayer;
        private int _defaultLayer;


        private void Update() {
            if (Mouse.current.leftButton.wasPressedThisFrame) {
                Hand(Mouse.current.position.ReadValue());
                this.gameObject.layer = _ignoreLayer;
            }

            if (UnityEngine.Input.GetMouseButton(0)) {
                Move(UnityEngine.Input.mousePosition);
            }

            if (UnityEngine.Input.GetMouseButtonUp(0)) {
                this.gameObject.layer = _defaultLayer;
                Destroy(_joint);
            }
        }
    }
}